package com.njupt.order.service.impl;

import com.njupt.common.pojo.TaotaoResult;
import com.njupt.mapper.TbOrderItemMapper;
import com.njupt.mapper.TbOrderMapper;
import com.njupt.mapper.TbOrderShippingMapper;
import com.njupt.order.jedis.JedisClient;
import com.njupt.order.jedis.JedisClientPool;
import com.njupt.order.pojo.OrderInfo;
import com.njupt.order.service.OrderService;
import com.njupt.pojo.TbItem;
import com.njupt.pojo.TbOrder;
import com.njupt.pojo.TbOrderItem;
import com.njupt.pojo.TbOrderShipping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.util.Date;
import java.util.List;


/**
 * @Author: XJL
 * @Description:
 * @Date: Create in 11:48 2018/6/6
 * @Modified By:
 **/
public class OrderServiceImpl implements OrderService {
    @Autowired
    private TbOrderMapper tbOrderMapper;
    @Autowired
    private TbOrderShippingMapper tbOrderShippingMappert;
    @Autowired
    private TbOrderItemMapper tbOrderItemMapper;
    @Autowired
    private JedisClient jedisClient;
    @Value("${ORDER_GEN_KEY}")
    private String ORDER_GEN_KEY;
    @Value("${ORDER_ID_PRE}")
    private String ORDER_ID_PRE;
    @Value("${ORDER_ITEM_ID_GEN}")
    private String ORDER_ITEM_ID_GEN;

    @Override
    public TaotaoResult createOrder(OrderInfo orderInfo) {
        //生成订单号。可以使用redis的incr
        if (!jedisClient.exists(ORDER_GEN_KEY)){
            jedisClient.set(ORDER_GEN_KEY,ORDER_ID_PRE);
        }
        String orderId = jedisClient.incr(ORDER_GEN_KEY).toString();
        //补全pojo属性
        orderInfo.setPostFee("0");
        orderInfo.setOrderId(orderId);
        //1、未付款，2、已付款，3、未发货，4、已发货，5、交易成功，6、交易关闭
        orderInfo.setStatus(1);
        Date date = new Date();
        orderInfo.setCreateTime(date);
        orderInfo.setUpdateTime(date);

        List<TbOrderItem> itemList = orderInfo.getOrderItems();

        //向订单表中插入数据
        tbOrderMapper.insert(orderInfo);
        for (TbOrderItem orderItem:itemList
             ) {
            String orderItemId = jedisClient.incr(ORDER_ITEM_ID_GEN).toString();
            orderItem.setId(orderItemId);
            orderItem.setOrderId(orderId);
            //向订单明细表中插入数据
            tbOrderItemMapper.insert(orderItem);
        }

        TbOrderShipping orderShipping = orderInfo.getOrderShipping();
        orderShipping.setOrderId(orderId);
        orderShipping.setUpdated(date);
        orderShipping.setCreated(date);

        //向物流表中插入数据
        tbOrderShippingMappert.insert(orderShipping);

        return TaotaoResult.ok(orderId);
    }
}
